import { deleteEyeDoctor, updateEyeInfo } from "@/services/order/api";
import { isNull, showMsg } from "@/utils/utils";
import { ModalForm, ProFormRadio, ProFormSelect, ProFormText } from "@ant-design/pro-form";
import { Col, Divider, FormInstance, Input, Row, message } from "antd";
import { ReactElement, useEffect, useRef, useState } from "react";
import { DeleteTwoTone, PlusOutlined } from "@ant-design/icons";
import { addEyeDoctor, getEyeDoctorList } from '@/services/order/api';
import { defocusOptions, eyeInfoColumn, museOptions } from "./EyeInfo";

const EyeInfoModal = (props: EyeInfoModalProps) => {

  const { visible, visibleChange, finishCallback, editData } = props;

  const formRef = useRef<FormInstance>();

  const [doctorName, setDoctorName] = useState<string>('');
  const [doctorListY, setDoctorListY] = useState([]);
  const [doctorListD, setDoctorListD] = useState([]);

  const onFinish = async (eyeValues: any) => {
    if (!isNull(eyeValues.right_degrees) && isNaN(eyeValues.right_degrees)) {
      message.error('右眼球镜输入有误，请修改');
      return;
    }
    if (!isNull(eyeValues.right_astig) && isNaN(eyeValues.right_astig)) {
      message.error('右眼柱镜输入有误，请修改');
      return;
    }
    if (!isNull(eyeValues.right_axial) && isNaN(eyeValues.right_axial)) {
      message.error('右眼轴位输入有误，请修改');
      return;
    }
    if (!isNull(eyeValues.before_right_version) && isNaN(eyeValues.before_right_version)) {
      message.error('右眼矫正前输入有误，请修改');
      return;
    }
    if (!isNull(eyeValues.after_right_version) && isNaN(eyeValues.after_right_version)) {
      message.error('右眼矫正后输入有误，请修改');
      return;
    }
    if (!isNull(eyeValues.left_degrees) && isNaN(eyeValues.left_degrees)) {
      message.error('左眼球镜输入有误，请修改');
      return;
    }
    if (!isNull(eyeValues.left_astig) && isNaN(eyeValues.left_astig)) {
      message.error('左眼柱镜输入有误，请修改');
      return;
    }
    if (!isNull(eyeValues.left_axial) && isNaN(eyeValues.left_axial)) {
      message.error('左眼轴位输入有误，请修改');
      return;
    }
    if (!isNull(eyeValues.before_left_version) && isNaN(eyeValues.before_left_version)) {
      message.error('左眼矫正前输入有误，请修改');
      return;
    }
    if (!isNull(eyeValues.after_left_version) && isNaN(eyeValues.after_left_version)) {
      message.error('左眼矫正后输入有误，请修改');
      return;
    }
    if (!isNull(eyeValues.pup_distance) && isNaN(eyeValues.pup_distance)) {
      message.error('总瞳距输入有误，请修改');
      return;
    }
    const tmp = {};
    for (const col of eyeInfoColumn) {
      tmp[col] = eyeValues[col];
    }
    const data = {
      ...tmp,
      order_id: editData?.order_id,
      right_degrees: !isNull(eyeValues.right_degrees) ? parseFloat(eyeValues.right_degrees) : 9999,
      right_astig: !isNull(eyeValues.right_astig) ? parseFloat(eyeValues.right_astig) : 9999,
      right_axial: !isNull(eyeValues.right_axial) ? parseInt(eyeValues.right_axial, 10) : 9999,
      left_degrees: !isNull(eyeValues.left_degrees) ? parseFloat(eyeValues.left_degrees) : 9999,
      left_astig: !isNull(eyeValues.left_astig) ? parseFloat(eyeValues.left_astig) : 9999,
      left_axial: !isNull(eyeValues.left_axial) ? parseInt(eyeValues.left_axial, 10) : 9999,
      doctor_id: eyeValues.doctor_id?.value,
      doctor_name: eyeValues.doctor_id?.label,
      optician_id: eyeValues.optician_id?.value,
      optician_name: eyeValues.optician_id?.label
    };

    if (editData?.order_id) {
      updateEyeInfo(data).then(res => {
        showMsg('更新成功', 'success');
        visibleChange(false);
        finishCallback?.();
      }).catch(error => {
        showMsg(error?.data?.errmsg);
      });
    }
  };

  // 格式化球镜柱镜数据
  const formatterData = (value: any) => {
    return isNull(value) ? '' : parseFloat(value) >= 0 ? `+${parseFloat(value).toFixed(2)}` : parseFloat(value).toFixed(2)
  }

  useEffect(() => {
    if (doctorListY.length == 0) {
      getEyeDoctorList().then(res => {
        setDoctorListData(res);
        if (!editData) return;
        setTimeout(() => {
          formRef.current?.setFieldsValue({
            optician_id: { value: editData.optician_id, label: editData.optician_name },
            doctor_id: { value: editData.doctor_id, label: editData.doctor_name }
          });
        }, 100);
      });
    }
    if (!editData) return;
    const dataValue = {};
    for (const v of eyeInfoColumn) {
      dataValue[v] = editData[v]
    }
    formRef.current?.setFieldsValue({
      ...dataValue,
      left_degrees: formatterData(editData.left_degrees),
      right_degrees: formatterData(editData.right_degrees),
      left_astig: formatterData(editData.left_astig),
      right_astig: formatterData(editData.right_astig),
      optician_id: { value: editData.optician_id, label: editData.optician_name },
      doctor_id: { value: editData.doctor_id, label: editData.doctor_name }
    });
  }, [editData]);

  const setDoctorListData = (res: any) => {
    const doctorListY: any = [], doctorListD: any = [];
    res?.record_list?.forEach(({ doctor_id, doctor_name, doctor_type }: any) => {
      if (doctor_type === 'Y') {
        doctorListY.push({ value: doctor_id, label: doctor_name });
      } else if (doctor_type === 'D') {
        doctorListD.push({ value: doctor_id, label: doctor_name });
      }
    });
    setDoctorListY(doctorListY);
    setDoctorListD(doctorListD);
  };

  const addDoctor = async (type: 'Y' | 'D') => {
    if ((doctorName ?? '').trim() === '') {
      showMsg(`请输入${type === 'Y' ? '验光师' : '就诊医生'}名字`);
      return;
    }
    try {
      const addRes = await addEyeDoctor(doctorName as string, type);
      const res = await getEyeDoctorList();
      setDoctorListData(res);
      await new Promise(resolve => setTimeout(resolve, 50));
      const labelInValueData = { value: addRes?.doctor_id, label: addRes?.doctor_name };
      formRef.current?.setFieldsValue(type === 'Y' ? { optician_id: labelInValueData } : { doctor_id: labelInValueData });
    } catch (err: any) {
      showMsg(err?.data?.errmsg);
    }
  };

  const doctorOptionRender = ({ value, label }: { value: string, label: string }, type: 'Y' | 'D') => {
    return <div style={{ position: "relative" }}>
      <span>{label}</span><DeleteTwoTone twoToneColor='red' style={{ position: "absolute", right: 0, top: 3, fontSize: 16 }} onClick={async e => {
        try {
          await deleteEyeDoctor(value);
          formRef.current?.setFieldsValue(type === 'Y' ? { optician_id: undefined } : { doctor_id: undefined });
          const res = await getEyeDoctorList();
          setDoctorListData(res);
        } catch (err: any) {
          showMsg(err?.data?.errmsg);
        }
        e.stopPropagation();
      }} />
    </div>;
  };

  const customDropdown = (menu: ReactElement, text: string, type: 'Y' | 'D') => {
    return (
      <div>
        {menu}
        <Divider style={{ margin: '4px 0' }} />
        <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'nowrap', padding: 8 }}>
          <Input style={{ flex: 'auto', height: 24 }} value={doctorName} onChange={e => setDoctorName(e.target.value)} />
          <a style={{ flex: 'none', padding: '8px', display: 'block', cursor: 'pointer' }} onClick={() => addDoctor(type)}>
            <PlusOutlined /> {text}
          </a>
        </div>
      </div>
    );
  };

  return (
    <ModalForm<any>
      formRef={formRef}
      title={`编辑配镜信息`}
      visible={visible}
      width={1200}
      // style={{minWidth: 1200}}
      layout="horizontal"
      modalProps={{ maskClosable: false, destroyOnClose: true }}
      onVisibleChange={visibleChange}
      onFinish={onFinish}
    >
      <Row gutter={12}>
        <Col style={{ paddingTop: 5 }}>
          <h4 style={{ width: 40 }}>用途</h4>
        </Col>
        <Col flex='1'>
          <ProFormRadio.Group labelCol={{ flex: '0 0 62px' }} label=" " colon={false} name="muse"
            fieldProps={{ defaultValue: 'S' }} options={museOptions} />
        </Col>
      </Row>
      <Row gutter={12}>
        <Col style={{ paddingTop: 5 }}>
          <h4 style={{ width: 40 }}>右眼R</h4>
        </Col>
        <Col flex={'0 0 15.8%'}>
          <ProFormText labelCol={{ flex: '0 0 62px' }} label="球镜" name="right_degrees" />
        </Col>
        <Col flex={'0 0 15.8%'}>
          <ProFormText labelCol={{ flex: '0 0 62px' }} label="柱镜" name="right_astig" />
        </Col>
        <Col flex={'0 0 15.8%'}>
          <ProFormText labelCol={{ flex: '0 0 62px' }} label="轴位" name="right_axial" />
        </Col>
        <Col flex={'0 0 15.8%'}>
          <ProFormText labelCol={{ flex: '0 0 62px' }} label="矫正前" name="right_rectify_bef" />
        </Col>
        <Col flex={'0 0 15.8%'}>
          <ProFormText labelCol={{ flex: '0 0 62px' }} label="矫正后" name="right_rectify_af" />
        </Col>
        <Col flex={'0 0 15.8%'}>
          <ProFormSelect labelCol={{ flex: '0 0 62px' }} label="离焦量" name="right_defocus"
            fieldProps={{ size: 'small', style: { width: '100%' } }} options={defocusOptions} />
        </Col>
      </Row>
      <Row gutter={12}>
        <Col style={{ marginTop: 5 }}>
          <h4 style={{ width: 40 }}>左眼L</h4>
        </Col>
        <Col flex={'0 0 15.8%'}>
          <ProFormText labelCol={{ flex: '0 0 62px' }} label="球镜" name="left_degrees" />
        </Col>
        <Col flex={'0 0 15.8%'}>
          <ProFormText labelCol={{ flex: '0 0 62px' }} label="柱镜" name="left_astig" />
        </Col>
        <Col flex={'0 0 15.8%'}>
          <ProFormText labelCol={{ flex: '0 0 62px' }} label="轴位" name="left_axial" />
        </Col>
        <Col flex={'0 0 15.8%'}>
          <ProFormText labelCol={{ flex: '0 0 62px' }} label="矫正前" name="left_rectify_bef" />
        </Col>
        <Col flex={'0 0 15.8%'}>
          <ProFormText labelCol={{ flex: '0 0 62px' }} label="矫正后" name="left_rectify_af" />
        </Col>
        <Col flex={'0 0 15.8%'}>
          <ProFormSelect labelCol={{ flex: '0 0 62px' }} label="离焦量" name="left_defocus"
            fieldProps={{ size: 'small', style: { width: '100%' } }} options={defocusOptions} />
        </Col>
      </Row>
      <Row gutter={12}>
        <Col style={{ marginTop: 5 }}>
          <h4 style={{ width: 40 }}>瞳距</h4>
        </Col>
        <Col flex={'0 0 15.8%'}>
          <ProFormText labelCol={{ flex: '0 0 62px' }} label="总瞳距" name="pup_distance" />
        </Col>
        <Col flex={'0 0 15.8%'}>
          <ProFormText labelCol={{ flex: '0 0 62px' }} label="瞳距右" name="pup_distance_right" />
        </Col>
        <Col flex={'0 0 15.8%'}>
          <ProFormText labelCol={{ flex: '0 0 62px' }} label="瞳距左" name="pup_distance_left" />
        </Col>
      </Row>
      <Row gutter={12}>
        <Col style={{ marginTop: 5 }}>
          <h4 style={{ width: 40 }}>瞳高</h4>
        </Col>
        <Col flex={'0 0 15.8%'}></Col>
        <Col flex={'0 0 15.8%'}>
          <ProFormText labelCol={{ flex: '0 0 62px' }} label="瞳高右" name="pup_high_right" />
        </Col>
        <Col flex={'0 0 15.8%'}>
          <ProFormText labelCol={{ flex: '0 0 62px' }} label="瞳高左" name="pup_high_left" />
        </Col>
      </Row>
      <Row gutter={12}>
        <Col style={{ flex: '0 0 52px' }}></Col>
        <Col flex={'0 0 31.6%'}>
          <ProFormText labelCol={{ flex: '0 0 62px' }} label="ADD" name="madd" />
        </Col>
        <Col flex={'0 0 63.2%'}>
          <ProFormText labelCol={{ flex: '0 0 62px' }} label={<span style={{ color: 'red' }}>特殊备注</span>} name="special_case" />
        </Col>
      </Row>
      <Row gutter={12}>
        <Col flex={'0 0 52px'}></Col>
        <Col flex={'0 0 31.6%'}>
          <ProFormText labelCol={{ flex: '0 0 62px' }} label="验光号" name="sight_no" />
        </Col>
        <Col flex={'0 0 31.6%'}>
          <ProFormSelect
            label="就诊医生"
            name="doctor_id"
            options={doctorListD}
            labelCol={{ flex: '0 0 62px' }}
            placeholder="请输入或选择就诊医生"
            style={{ width: '100%' }}
            fieldProps={{
              className: "doctor-select",
              optionFilterProp: 'children',
              labelInValue: true,
              showSearch: true,
              filterOption: (input, option) => (option?.label as any)?.includes(input),
              optionItemRender: item => doctorOptionRender(item, 'D'),
              dropdownRender: menu => customDropdown(menu, '新增就诊医生', 'D'),
              onDropdownVisibleChange: open => { if (open) setDoctorName(''); }
            }}
          />
        </Col>
        <Col flex={'0 0 31.6%'}>
          <ProFormSelect
            label="验光师"
            name="optician_id"
            options={doctorListY}
            labelCol={{ flex: '0 0 62px' }}
            placeholder="请输入或选择验光师"
            style={{ width: '100%' }}
            fieldProps={{
              className: "doctor-select",
              optionFilterProp: 'children',
              labelInValue: true,
              showSearch: true,
              filterOption: (input, option) => (option?.label as any)?.includes(input),
              optionItemRender: item => doctorOptionRender(item, 'Y'),
              dropdownRender: menu => customDropdown(menu, '新增验光师', 'Y'),
              onDropdownVisibleChange: open => { if (open) setDoctorName(''); }
            }}
          />
        </Col>
      </Row>
    </ModalForm>
  );
};

export default EyeInfoModal;

interface EyeInfoModalProps {
  visible: boolean;
  visibleChange: (visible: boolean) => void;
  finishCallback?: () => void;
  editData?: any;
}
